//
//  FindViewController.m
//  Ting
//
//  Created by 安静的美男子 on 14/11/12.
//  Copyright (c) 2014年 安静的美男子. All rights reserved.
//

#import "FindViewController.h"
#import "GetData.h"
#import "TopTableViewCell.h"
#import "CollectTableViewCell.h"
#import "NextViewController.h"
#import "FourTableViewCell.h"
#import "AudioStreamerManager.h"
#import "BoZhuViewController.h"
#import "SegViewController.h"
@interface FindViewController ()<UITableViewDataSource,UITableViewDelegate,Push,change,UIAlertViewDelegate>

@end

@implementation FindViewController
-(void)viewDidDisappear:(BOOL)animated
{
    [self.Timer invalidate];
    _Timer =nil;

}
-(void)viewWillAppear:(BOOL)animated
{
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    self.model = audioManager.Mymodel;
    
   
    if (audioManager.flag) {
      
        if (!_Timer) {
//            self.Timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(zhuan) userInfo:nil repeats:YES];
            
            self.Timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(zhuan) userInfo:nil repeats:YES];
        }

        //将定时器加入循环
        //循环用于系统页面响应,定时器和进程
//                [[NSRunLoop currentRunLoop] addTimer:_Timer forMode:NSDefaultRunLoopMode];
        
            
        [_Timer setFireDate:[NSDate distantPast]];

        
        
        
    }
    else
    {
        
        [_Timer setFireDate:[NSDate distantFuture]];
        
//        if ([_Timer isValid]) {
//            永久停止
//            [self.Timer invalidate];
//            _Timer =nil;
//        }

        
    }
    
}
-(void)zhuan
{
    self.play.transform = CGAffineTransformRotate(self.play.transform,2 * M_PI / 60.0 /100);
//    if (_model.coverLarge) {
    [self.play sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
    //自动下一曲
    
//    }
//    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    
//    if (CMTimeGetSeconds(audioManager.PLAYER.currentItem.currentTime)
//       == CMTimeGetSeconds(audioManager.PLAYER.duration)) {
//    }
//    if (audioManager.num + 1 != audioManager.Mydata.count) {
//        
//        
//        [audioManager playWithData:audioManager.Mydata num:audioManager.num + 1 model:audioManager.Mydata[audioManager.num + 1]];
//    }
}
-(void)ReGetData
{
    if (_downArr.count == 0 ||_TopArr.count == 0 ||_DataArr.count == 0) {
        [self.mbview removeFromSuperview];
        UIAlertView * aleart = [[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络连接不好是否重试" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [aleart show];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self getData];
        [self.view addSubview:_mbview];
        [self performSelector:@selector(ReGetData) withObject:self afterDelay:5];


    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIColor * color = [UIColor whiteColor];
    
    
    
       //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    
    NSDictionary * dict=[NSDictionary dictionaryWithObject:color forKey:UITextAttributeTextColor];
    
      //大功告成
    
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    self.title = @"发现";

    
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    
    _flag = NO;
    _height = 75 * 3;
    
    self.DataArr = [NSMutableArray array];
    self.TopArr = [NSMutableArray array];
    self.downArr = [NSMutableArray array];
    
    [self getData];
 
    if (!_table) {
        
        self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.height - 64 - 44) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.showsVerticalScrollIndicator = NO;
        
        [self.view addSubview:_table];
       
        
        
    }
    self.mbview = [[MBProgressHUD alloc] initWithView:self.view];
    self.mbview.labelText = @"正在努力加载中...";
    [self.mbview setMode:MBProgressHUDModeIndeterminate];
    [self.mbview show:YES];
    [self.view addSubview:self.mbview];
//    [self performSelector:@selector(ReGetData) withObject:self afterDelay:2 inModes:nil];
    //延迟5S判断有没有网络
    [self performSelector:@selector(ReGetData) withObject:self afterDelay:10];
    
    
    //button方法
//    [self.information addTarget:self action:@selector(GotoInformation) forControlEvents:UIControlEventTouchUpInside];

    UIView *black = [[UIView alloc]initWithFrame:CGRectMake(64 * 2, 568 - 64, 64, 64)];
    [self.view addSubview:black];
    black.layer.cornerRadius = 32;
    black.clipsToBounds = YES;

    black.backgroundColor = [UIColor blackColor];
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.play.frame = CGRectMake(0, 0, 60, 60);
    self.play.center = black.center;
    
    [self.view addSubview:self.play];
    
    self.play.layer.cornerRadius = 30;
    [self.view bringSubviewToFront:self.play];
    self.play.clipsToBounds = YES;
    
    [self.play addTarget:self action:@selector(GotoPlay) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.play sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.model.coverLarge]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"123.png"]];
    self.view.backgroundColor = [UIColor blackColor];

}
-(void)GotoSetting
{
    SettingViewController *vc = [[SettingViewController alloc]init];
    [self.navigationController pushViewController:vc animated:NO];
    
}
-(void)GotoAlbum
{
    AlbumViewController *vc = [[AlbumViewController alloc]init];
    vc.title =@"下载";
    [vc.navigationItem setHidesBackButton:YES];

    [self.navigationController pushViewController:vc animated:NO];
    
}
-(void)GotoPlay
{
    PlayViewController *vc = [[PlayViewController alloc]init];
    AudioStreamerManager *audioManager = [AudioStreamerManager shareInstanceManager];
    vc.model = audioManager.Mymodel;
    vc.DataSource = audioManager.Mydata;
    /**
     *  number不记录
     */

//    vc.number = audioManager.num;
    vc.num = [NSString stringWithFormat:@"%ld",audioManager.num];
    
    
    [self presentViewController:vc animated:YES completion:nil];
     
}
     
-(void)GotoInformation
{
    InformationViewController *vc = [[InformationViewController alloc]init];
    [vc.navigationItem setHidesBackButton:YES];
    vc.title = @"最火播主";
    
    [self.navigationController pushViewController:vc animated:NO];
    
}

-(void)getData
{
    
    GetData *data = [[GetData alloc]init];
    [data getDataURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/m/super_explore_index?device=iPhone&includeActivity=true&picVersion=5&scale=2"] dic:nil block:^(id result) {
        if ([result isEqual:@"error"]) {
            [self ReGetData];
            
        }

        self.TopArr = [[result objectForKey:@"focusImages"]objectForKey:@"list"];
        self.DataArr = [[result objectForKey:@"categories"] objectForKey:@"data"];
        
        [self.table reloadData];
    }];
     GetData *Fourdata = [[GetData alloc]init];
    [Fourdata getDataURL:[NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=&condition=all&device=iPhone&page=1&per_page=20&status=0&tag_name="] dic:nil block:^(id result) {
        
        if ([result isEqual:@"error"]) {
            [self ReGetData];
            
        }
        else
        {
        self.downArr = [result objectForKey:@"list"];
        [self.table reloadData];
        
        }
    }];
    
    
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        
        static NSString *ident =@"cell";
        TopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident];
        if (!cell) {
            cell = [[TopTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ident];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        [cell setArr:_TopArr];
        return cell;
    }else if (indexPath.row == 1)
    {
        static NSString *ident1 =@"collect";
        CollectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ident1];
        if (!cell) {
            cell = [[CollectTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ident1];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        [cell setCollectionArr:_DataArr flag:_flag];
    
        cell.delegate = self;
        
        
        return cell;
    }else
    {
        static NSString *four = @"four";
        FourTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:four];
        if (!cell) {
            cell = [[FourTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:four];
            
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        [cell.view1 setViewWithArr:_downArr num:0];
        [cell.view2 setViewWithArr:_downArr num:1];
        [cell.view3 setViewWithArr:_downArr num:2];
        [cell.view4 setViewWithArr:_downArr num:3];
        [cell.more addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];
        
        [cell.view1.button addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];
        [cell.view2.button addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];[cell.view3.button addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];[cell.view4.button addTarget:self action:@selector(push:) forControlEvents:UIControlEventTouchUpInside];
        
        
        return cell;
        
    }
    
    
}
-(void)push:(UIButton *)sender
{
    
    
    if (sender.tag) {
        BoZhuViewController *vc = [[BoZhuViewController alloc]init];
        
        vc.MyId = [NSString stringWithFormat:@"%@",[_downArr[sender.tag - 1] objectForKey:@"id"]];
        vc.title = [NSString stringWithFormat:@"%@",[_downArr[sender.tag - 1] objectForKey:@"title"]];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        SegViewController *vc = [[SegViewController alloc]init];
        vc.name = @"";
        vc.url = @"all";
        vc.title = @"全部";
        
        [self.navigationController pushViewController:vc animated:YES];

        
    }
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_downArr.count != 0 && _TopArr .count !=0 && _DataArr.count != 0) {
        [self.mbview removeFromSuperview];
        return 3;
    }
    
    return 0;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return 150;
    }else if( indexPath.row == 1)
    {
        
        return _height;
    }else
    {
       return  400;
        
    }
    
}
-(void)changViewWithFlag:(BOOL)flag
{
    self.flag = flag;
    if (_flag == NO) {
        _height = 75 * 3;
        [_table reloadData];
    }else
    {
        _height = 75 * 6;
        [_table reloadData];
    }
}
-(void)pushViewWithnum:(NSInteger)num
{

    NextViewController *vc = [[NextViewController alloc]init];
    vc.name = [_DataArr[num] objectForKey:@"name"];
    vc.title = [_DataArr[num] objectForKey:@"title"];
    
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
